<!-- 表字段 -->
<template>
  <div class="table-fields" ref="tableFieldRef">
    <div class="table-top" ref="tableTopRef">
      <el-input
        size="small"
        placeholder="请输入关键词"
        v-model.trim="searchText"
        @input="handleSearch"
        style="width: 200px"
      ></el-input>
      <el-button
        v-if="modelStatus === 0"
        size="small"
        type="primary"
        @click="addField"
        >添加</el-button
      >
    </div>
    <el-table
      :key="refresh"
      :data="useFiledList"
      :max-height="fixedHeight"
      :cell-style="{ color: '#333333' }"
      :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
    >
      <el-table-column
        prop="columnField"
        label="字段名"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnField"
            size="small"
            placeholder="请输入字段名"
          ></el-input>
          <template v-else>
            {{ scope.row.columnField }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnType"
        label="字段类型"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.columnTypeId"
            size="small"
            placeholder="请选择字段类型"
          >
            <el-option
              v-for="i in filedOptions"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
          <template v-else>
            {{ scope.row.columnType }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnPrecision"
        label="精度"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnPrecision"
            size="small"
            placeholder="请输入精度"
          ></el-input>
          <template v-else>
            {{ scope.row.columnPrecision }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnScale"
        label="标度"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnScale"
            size="small"
            placeholder="请输入标度"
          ></el-input>
          <template v-else>
            {{ scope.row.columnScale }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="columnRemark"
        label="注释"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model.trim="scope.row.columnRemark"
            size="small"
            placeholder="请输入注释"
          ></el-input>
          <template v-else>
            {{ scope.row.columnRemark }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="isAllowNullStatus"
        label="是否为空"
        min-width="150"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.isAllowNull"
            size="small"
            placeholder="请选择是否为空"
          >
            <el-option
              v-for="i in allowNullOptions"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            ></el-option>
          </el-select>
          <template v-else>
            <template v-if="scope.row.isAllowNull === 0"> 否 </template>
            <template v-else-if="scope.row.isAllowNull === 1"> 是 </template>
            <template v-else> --- </template>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        v-if="modelStatus === 0"
        label="操作"
        fixed="right"
        align="center"
        width="250"
      >
        <template slot-scope="scope">
          <template v-if="scope.row.isEdit">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="saveField(scope.row)"
              >保存</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="cancelOpera(scope.row, scope.$index)"
              >取消</el-link
            >
          </template>
          <template v-else>
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="editField(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="deleteField(scope.row, scope.$index)"
              >删除</el-link
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "TableFields",
  props: {
    tableFields: {
      type: Array,
      default: () => [],
    },
    modelStatus: {
      type: Number,
      default: null,
    },
    filedOptions: {
      type: Array,
      default: () => [],
    },
    modelInfo: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      fixedHeight: 500,
      refresh: 0,
      searchText: null,
      useFiledList: [],
      allowNullOptions: [
        {
          value: 0,
          label: "否",
        },
        {
          value: 1,
          label: "是",
        },
      ],
      // 存储字段信息set
      fieldNameSet: new Set(),
      // 记录当前编辑字段行
      currentRow: {}
    };
  },
  watch: {
    tableFields: {
      handler(val, olVal) {
        console.log(
          "%c [ val ]-247",
          "font-size:13px; background:pink; color:#bf2c9f;",
          val
        );
        this.searchText = null;
        this.useFiledList = cloneDeep(val);
        for (let i of val) {
          this.fieldNameSet.add(i.columnField);
        }
      },
      immediate: true
    },
  },
  mounted() {
    // 高度计算后 修改this.refresh 让vue重新渲染table
    this.fixedHeight =
      this.$refs.tableFieldRef.clientHeight -
      this.$refs.tableTopRef.clientHeight;
    this.refresh++;
  },
  methods: {
    handleSearch(val) {
      if (val) {
        const filterList = this.tableFields.filter((ele) =>
          ele.columnField.toLowerCase().includes(val.toLowerCase())
        );
        this.useFiledList = filterList;
      } else {
        this.useFiledList = this.tableFields;
      }
    },
    addField() {
      this.useFiledList.push({
        columnField: null,
        columnType: null,
        columnTypeId: null,
        columnPrecision: null,
        columnScale: null,
        columnRemark: null,
        isAllowNullStatus: null,
        isEdit: true,
        isAdd: true,
      });
    },
    editField(row) {
      this.currentRow = cloneDeep(row)
      // 编辑时先移除当前行columnField
      this.fieldNameSet.delete(row.columnField);
      this.$set(row, "isEdit", true);
    },
    deleteField(row, index) {
      this.$confirm("是否删除该字段？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.useFiledList.splice(index, 1);
          this.fieldNameSet.delete(row.columnField)
          const subForm = {
            ...this.modelInfo.localModelResp,
            modelFieldList: this.useFiledList,
          };
          this.$axios
            .post(
              this.$api.dataConnection.physicalModel.updateModelInfo,
              subForm
            )
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success(res.data.message || "操作成功");
              } else {
                this.$message.warning(res.data.message);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    saveField(row) {
      if (!this.checkFields(row)) {
        return;
      }
      this.$set(row, "isEdit", false);
      this.fieldNameSet.add(row.columnField);
      if (row.isAdd) {
        row.isAdd = false
      }
      let item = this.filedOptions.find((i) => i.value === row.columnTypeId);
      this.$set(row, "columnType", item ? item.label : "");
      const subForm = {
        ...this.modelInfo.localModelResp,
        modelFieldList: this.useFiledList,
      };
      this.$axios
        .post(this.$api.dataConnection.physicalModel.updateModelInfo, subForm)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message || "操作成功");
          } else {
            this.$message.warning(res.data.message);
          }
        });
    },
    checkFields(row) {
      // console.log(
      //   "%c [ row ]-336",
      //   "font-size:13px; background:pink; color:#bf2c9f;",
      //   row
      // );
      if (row.columnField === "" || row.columnField === null) {
        this.$message.warning("字段名不能为空!");
        return false;
      }
      if (this.fieldNameSet.has(row.columnField)) {
        this.$message.warning("字段名禁止重复!");
        return false;
      }
      if (row.columnTypeId === null) {
        this.$message.warning("字段类型不能为空!");
        return false;
      }
      if (row.columnPrecision === "" || row.columnPrecision === null) {
        this.$message.warning("字段精度不能为空!");
        return false;
      }
      return true;
    },
    cancelOpera(row, index) {
      if (row.id || !row.isAdd) {
        // 复原信息
        for (let k in row) {
          row[k] = this.currentRow[k]
        }
        this.fieldNameSet.add(this.currentRow.columnField);
      } else {
        this.useFiledList.splice(index, 1);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.table-fields {
  height: 100%;
}

.table-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.ontology-edit {
  padding: 0 10px;

  & + .ontology-edit {
    border-left: 1px solid #dddddd;
  }
}
</style>
